//
//  PublishActViewController.m
//  yunyan
//
//  Created by chirui on 2018/5/7.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "PublishActViewController.h"
#import "WSImagePickerView.h"
#import "ReleaseResultsView.h"
#import "MyPictureViewController.h"

#define kScreenWidth        [[UIScreen mainScreen] bounds].size.width
#define kScreenHeight       [[UIScreen mainScreen] bounds].size.height

@interface PublishActViewController (){
    
    NSArray * imageArray;
    
    ReleaseResultsView *clearView;
}

@property (nonatomic,strong) SZTextView * titleSztTextView;

@property (nonatomic,strong) SZTextView * messageSztTextView;

@property (nonatomic, strong) WSImagePickerView *pickerView;

@property (nonatomic,strong) UIButton * sureBtn;

@end

@implementation PublishActViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   [self customNaviItemTitle:@"发布详情" isLeft:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(goToCent:)
                                                 name: @"goToCent"
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NotgoToCent:)
                                                 name: @"NotgoToCent"
                                               object:nil];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [self creatUi];
}

-(void)creatUi{
    
    self.titleSztTextView =[[SZTextView alloc]initWithFrame:CGRectMake(10, 10, WIDTH-20, 80)];
    self.titleSztTextView.placeholder = @"这里输入标题，不超过30个字符";
    self.titleSztTextView.placeholderTextColor = [UIColor lightGrayColor];
    self.titleSztTextView.font =[UIFont systemFontOfSize:15];
    [self.view addSubview:self.titleSztTextView];
    
    UIView * photoView = [[UIView alloc]initWithFrame:CGRectMake(10, 100, WIDTH-20, 255)];
    photoView.layer.cornerRadius = 4.f;
    photoView.layer.masksToBounds = YES;
    photoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:photoView];
    
    
    
    self.messageSztTextView =[[SZTextView alloc]initWithFrame:CGRectMake(10, 10, WIDTH-20, 110)];
    self.messageSztTextView.placeholder = @"这里输入文字内容，(100字以内)";
    self.messageSztTextView.placeholderTextColor = [UIColor lightGrayColor];
    self.messageSztTextView.font =[UIFont systemFontOfSize:15];
    [photoView addSubview:self.messageSztTextView];
    
    UILabel * messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 110, WIDTH -20, 20)];
    messageLabel.text = @"  注：最多选择六张照片";
    messageLabel.font = [UIFont systemFontOfSize:13];
    messageLabel.textColor = [UIColor lightGrayColor];
    [photoView addSubview:messageLabel];
    
    WSImagePickerConfig *config = [WSImagePickerConfig new];
    config.itemSize = CGSizeMake(50, 50);
    config.photosMaxCount = 6;
    
    WSImagePickerView *pickerView = [[WSImagePickerView alloc] initWithFrame:CGRectMake(0, 130, kScreenWidth-20, 0) config:config];
    //Height changed with photo selection
//    __weak typeof(self) weakSelf = self;
    
//    NSLayoutConstraint *photoViewHieghtConstraint = [nsla]
//
//    pickerView.viewHeightChanged = ^(CGFloat height) {
//        weakSelf.photoViewHieghtConstraint.constant = height;
//        [weakSelf.view setNeedsLayout];
//        [weakSelf.view layoutIfNeeded];
//    };
    pickerView.navigationController = self.navigationController;
    [photoView addSubview:pickerView];
    self.pickerView = pickerView;
    
    //refresh superview height
    [pickerView refreshImagePickerViewWithPhotoArray:nil];
    
    //确定按钮
    self.sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sureBtn.frame = CGRectMake(15, CGRectGetMaxY(photoView.frame)+20, WIDTH -30, 50);
    self.sureBtn.backgroundColor = RGBA(81, 158, 238, 1);
    self.sureBtn.enabled =YES;
    self.sureBtn.layer.masksToBounds = YES;
    self.sureBtn.layer.cornerRadius = 5;
    [self.sureBtn setTitle: @"发布" forState:UIControlStateNormal];
    [self.sureBtn addTarget:self action:@selector(sureBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sureBtn];
    
}

-(void)sureBtnClicked{
    
    imageArray = [_pickerView getPhotos];
    NSLog(@"%@",imageArray);
    
    if (_titleSztTextView.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入标题");
        return;
    }
    if (_messageSztTextView.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入内容");
        return;
    }
    
    if (imageArray.count ==0) {
        
        SHuiMBhudTextTimeStr(@"请上传图片");
        return;
    }
    [self upImageAndTitleRequest];
    
//    [[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"共选择了%@张照片",@(array.count)] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}

-(void)upImageAndTitleRequest{
    
  
    
    NSMutableArray * img = @[].mutableCopy;
    if (img) {
        [img removeAllObjects];
    }
    for (int i = 0; i<imageArray.count; i++) {
        
        NSData *data = UIImageJPEGRepresentation(imageArray[i], 0.3);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
        
        [img addObject:imageStr];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:img
                                                       options:kNilOptions
                                                         error:nil];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    
    NSLog(@" img  = %@  ima.count = %ld",img,img.count);
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"title":_titleSztTextView.text,
                           @"content":_messageSztTextView.text,
                           @"img":jsonString
                           };
    
    NSLog(@"dic = %@",dic);
    
    
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(new_publish_photo_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (clearView) {
            
            [clearView removeFromSuperview];
        }
        clearView = [[ReleaseResultsView alloc]init];
        [clearView initResultsViewWithClear:NO];
        clearView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [[UIApplication sharedApplication].keyWindow addSubview:clearView];
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        SHuiMBHidleYes;
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"请稍后再试");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"认证失败");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

-(void)goToCent:(NSNotification *)notification{
    
    [clearView removeFromSuperview];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"goToCent" object:self];
    MyPictureViewController * pict =[[MyPictureViewController alloc]init];
    pict.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:pict animated:YES];
}

-(void)NotgoToCent:(NSNotification *)notification{
    
    [clearView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
